package com.jky.trial.controller;

import com.alibaba.fastjson.JSONObject;
import com.jky.trial.common.DateUtil;
import com.jky.trial.common.poi.WordUtil;
import com.jky.trial.constant.DataStatus;
import com.jky.trial.entity.Category;
import com.jky.trial.entity.Record;
import com.jky.trial.entity.Task;
import com.jky.trial.entity.User;
import com.jky.trial.service.*;
import com.jky.trial.vo.CategoryVo;
import com.jky.trial.vo.ProjectVo;
import com.jky.trial.vo.RecordVo;
import com.jky.trial.vo.TaskVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api/v1/poi")
public class PoiController {

    private WordUtil wordUtil;
    private TaskService taskService;
    private RecordService recordService;
    private ProjectService projectService;
    private UserService userService;
    private CategoryService categoryService;

    @Autowired
    PoiController(WordUtil wordUtil,
                  CategoryService categoryService,
                  RecordService recordService,
                  UserService userService,
                  ProjectService projectService, TaskService taskService) {
        this.categoryService = categoryService;
        this.recordService = recordService;
        this.userService = userService;
        this.wordUtil = wordUtil;
        this.taskService = taskService;
        this.projectService = projectService;
    }


    @GetMapping("/word/{id}")
    public OutputStream get(@PathVariable Integer id, HttpServletResponse response) {
        try {
            response.setContentType("application/msword;charset=UTF-8");
            ProjectVo project = projectService.moreDetail(id);
            TaskVo taskVo = new TaskVo();
            taskVo.setProjectId(id);
            taskVo.setSize(Integer.MAX_VALUE);
            taskVo.setDeleted(false);
            List<TaskVo> list = taskService.list(taskVo);
            CategoryVo categoryVo = new CategoryVo();
            categoryVo.setType(DataStatus.CATEGORY_DATA_TYPE_SPECS.getVal());
            categoryVo.setRType(DataStatus.RELATION_TYPE_PROJECT_SPEC.getVal());
            categoryVo.setRSourceId(id);

            Task task = new Task();
            task.setProjectId(id);
            task.setDeleted(false);
            int total = (int) taskService.count(task);
            project.setNumTotal(String.valueOf(total));//勘探点数
            task.setStatus(DataStatus.TASK_STATUS_ASSIGN.getVal());
            int unhole = (int) taskService.count(task);

            project.setNumHole(String.valueOf(total - unhole));//取孔数
            Record record = new Record();
            record.setProjectId(id);
            record.setDeleted(false);
            //标惯
            record.setType(DataStatus.LOG_SUB_TYPE_RECORD_BIAOGUAN.getVal());
            int biaoguanNum = (int) recordService.count(record);
            project.setNumBiaoguan(String.valueOf(biaoguanNum));

            CategoryVo zj = new CategoryVo();
            List<CategoryVo> zjList = (List<CategoryVo>) categoryService.zjList(zj).getList();
            int numDp = 0, numXp = 0;
            if (zjList.size() > 0)
                for (CategoryVo item : zjList) {
                    if (item.getRemark().toLowerCase().indexOf("xy") > -1) {
                        numXp++;
                    } else if (item.getRemark().toLowerCase().indexOf("ddp") > -1) {
                        numDp++;
                    }
                }
            //车载钻机数量
            project.setNumDP(String.valueOf(numDp));
            //台式钻机数量
            project.setNumXP(String.valueOf(numXp));

            List<CategoryVo> specs = categoryService.listByDr(categoryVo);
            project.setSpecs(specs);
            String fileName = URLEncoder.encode(project.getName() + "勘察纲要" + DateUtil.dateToStr(new Date(), "yyyyMMdd"), "UTF-8");
            response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".docx");// 组装附件名称和格式
            response.setCharacterEncoding("UTF-8");
            return wordUtil.writeContent(response.getOutputStream(), list, project);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @GetMapping("/record/word/{id}")
    public OutputStream record(@PathVariable Integer id, HttpServletResponse response) {
        try {
            response.setContentType("application/msword;charset=UTF-8");
            ProjectVo project = projectService.moreDetail(id);
            RecordVo recordVo = new RecordVo();
            recordVo.setProjectId(id);
            recordVo.setSize(Integer.MAX_VALUE);
            recordVo.setDeleted(false);
            recordVo.setType(DataStatus.LOG_SUB_TYPE_RECORD_HUICI.getVal());
            List<RecordVo> list = recordService.list(recordVo);
            list.forEach(item -> {
                //土样
                RecordVo record = new RecordVo();
                record.setType(DataStatus.LOG_SUB_TYPE_RECORD_QUTU.getVal());
                record.setTargetId(item.getTargetId());
                record.setHcId(item.getId());
                record.setDeleted(false);
                record.setSize(Integer.MAX_VALUE);
                item.setQutuVo(recordService.list(record));
                //标贯
                record.setType(DataStatus.LOG_SUB_TYPE_RECORD_BIAOGUAN.getVal());
                item.setBiaoguanVo(recordService.list(record));
                //动探
                record.setType(DataStatus.LOG_SUB_TYPE_RECORD_DONGTAN.getVal());
                item.setDongtanVo(recordService.list(record));
            });
            TaskVo taskVo = new TaskVo();
            taskVo.setDeleted(false);
            taskVo.setProjectId(id);
            taskVo.setSize(Integer.MAX_VALUE);
            List<TaskVo> tasks = taskService.list(taskVo);
            this.formatData(tasks, project, recordVo);
            String fileName = URLEncoder.encode(project.getName() + "描述记录" + DateUtil.dateToStr(new Date(), "yyyyMMdd"), "UTF-8");
            response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".docx");// 组装附件名称和格式
            response.setCharacterEncoding("UTF-8");
            return wordUtil.writeRecordList(response.getOutputStream(), list, tasks);
        } catch (
                IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 单个勘探点勘探记录数字化查看.
     *
     * @param id
     * @param tId
     * @return
     */
    @GetMapping("/record/list/{tId}")
    public List record(@PathVariable Integer tId) {
        Task task = taskService.detail(tId);
//        Integer id =task.getProjectId();
        RecordVo recordVo = new RecordVo();
        recordVo.setProjectId(task.getProjectId());
        recordVo.setSize(Integer.MAX_VALUE);
        recordVo.setDeleted(false);
        recordVo.setType(DataStatus.LOG_SUB_TYPE_RECORD_HUICI.getVal());
        recordVo.setTargetId(tId);
        List<RecordVo> list = recordService.list(recordVo);
        list.forEach(item -> {
            //土样
            RecordVo record = new RecordVo();
            record.setType(DataStatus.LOG_SUB_TYPE_RECORD_HUICI.getVal());
            record.setTargetId(item.getTargetId());
            record.setHcId(item.getId());
            record.setDeleted(false);
            item.setQutuVo(recordService.list(record));
            //标贯
            record.setType(DataStatus.LOG_SUB_TYPE_RECORD_BIAOGUAN.getVal());
            item.setBiaoguanVo(recordService.list(record));
            //动探
            record.setType(DataStatus.LOG_SUB_TYPE_RECORD_DONGTAN.getVal());
            item.setDongtanVo(recordService.list(record));
        });
//        TaskVo taskVo = new TaskVo();
//        taskVo.setDeleted(false);
//        taskVo.setProjectId(id);
//        taskVo.setSize(Integer.MAX_VALUE);
//        List<TaskVo> tasks = taskService.list(taskVo);
        return wordUtil.writeRecordListV2(list);

    }


    @GetMapping("/record/word/taskId/{id}")
    public OutputStream taskRecord(@PathVariable Integer id, HttpServletResponse response) {
        try {
            response.setContentType("application/msword;charset=UTF-8");
            TaskVo taskVo = taskService.detail(id);
            ProjectVo project = projectService.moreDetail(taskVo.getProjectId());
            RecordVo recordVo = new RecordVo();
            recordVo.setProjectId(taskVo.getProjectId());
            recordVo.setSize(Integer.MAX_VALUE);
            recordVo.setDeleted(false);
            recordVo.setType(DataStatus.LOG_SUB_TYPE_RECORD_HUICI.getVal());

            List<RecordVo> list = recordService.list(recordVo);
            list.forEach(item -> {
                //土样
                RecordVo record = new RecordVo();
                record.setType(DataStatus.LOG_SUB_TYPE_RECORD_HUICI.getVal());
                record.setTargetId(item.getTargetId());
                record.setHcId(item.getId());
                record.setDeleted(false);
                item.setQutuVo(recordService.list(record));
                //标贯
                record.setType(DataStatus.LOG_SUB_TYPE_RECORD_BIAOGUAN.getVal());
                item.setBiaoguanVo(recordService.list(record));
                //动探
                record.setType(DataStatus.LOG_SUB_TYPE_RECORD_DONGTAN.getVal());
                item.setDongtanVo(recordService.list(record));
            });
            List<TaskVo> tasks = new ArrayList<>();
            tasks.add(taskVo);
            formatData(tasks, project, recordVo);
            String fileName = URLEncoder.encode(project.getName() + "描述记录" + DateUtil.dateToStr(new Date(), "yyyyMMdd"), "UTF-8");
            response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".docx");// 组装附件名称和格式
            response.setCharacterEncoding("UTF-8");
            return wordUtil.writeRecordList(response.getOutputStream(), list, tasks);
        } catch (
                IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void formatData(List<TaskVo> tasks, ProjectVo project, RecordVo recordVo) {
        for (int i = 0; i < tasks.size(); i++) {
            TaskVo taskVo1 = tasks.get(i);
            taskVo1.setProjectName(project.getName());
            taskVo1.getAssigneeId();
            //钻机组
            CategoryVo categoryVo = new CategoryVo();
            categoryVo.setRTargetId(taskVo1.getAssigneeId());
            categoryVo.setRType(DataStatus.RELATION_TYPE_JZ_DESCER.getVal());
            categoryVo.setProjectId(project.getId());
            categoryVo.setType(DataStatus.CATEGORY_DATA_TYPE_JZ.getVal());
            categoryVo.setpId(project.getId());
            Category category = categoryService.selectZjzByDescer(categoryVo);
            if (category != null) {
                taskVo1.setZtjzName(category.getName());
                taskVo1.setModal(category.getRemark());
                taskVo1.setMethod(category.getRemark2());
            }
            //水位
            recordVo.setType(DataStatus.LOG_SUB_TYPE_RECORD_SHUIWEI.getVal());
            recordVo.setTargetId(taskVo1.getId());
            List<RecordVo> shuiwei = recordService.list(recordVo);

            if (shuiwei.size() != 0) {
                RecordVo shuiwei1 = shuiwei.get(0);
                taskVo1.setWaterEndAt(trimNull(shuiwei1.getMethod4()));
                taskVo1.setWaterStartAt(trimNull(shuiwei1.getMethod2()));
                if (shuiwei1.getRemark1() != null) {
                    taskVo1.setWaterStartDateAt(DateUtil.dateToStr(DateUtil.strToDate(shuiwei1.getRemark1()), "MM月dd日"));
                } else {
                    taskVo1.setWaterStartDateAt("");
                }
                JSONObject js = JSONObject.parseObject(shuiwei1.getMethod3());
                if (js.getString("method3") != null) {
                    taskVo1.setWaterEndDateAt(DateUtil.dateToStr(DateUtil.strToDate(js.getString("method3")), "MM月dd日"));
                } else {
                    taskVo1.setWaterEndDateAt("");
                }
            } else {
                taskVo1.setWaterEndAt("/");
                taskVo1.setWaterStartAt("/");
                taskVo1.setWaterEndDateAt("/");
                taskVo1.setWaterStartDateAt("/");
            }
            //孔深
            RecordVo record = new RecordVo();
            record.setType(DataStatus.LOG_SUB_TYPE_RECORD_HUICI.getVal());
            record.setTargetId(taskVo1.getId());
            record.setDeleted(false);
            Float lastDepth = recordService.selectMaxDeep(record);
            if (lastDepth == null) lastDepth = Float.parseFloat("0.0");
            taskVo1.setHoleDeep(lastDepth.toString());
            if (project.getDutyId() != null) {
                User user = userService.detail(project.getDutyId());
                if (user != null)
                    taskVo1.setDuty(user.getName());
            }
            if (taskVo1.getAssigneeId() != null) {
                User user1 = userService.detail(taskVo1.getAssigneeId());
                if (user1 != null)
                    taskVo1.setAssigneeName(user1.getName());
            }
        }
    }


    String trimNull(String str) {
        return str != null ? str : "";
    }


}
